package com.itheima.Controller;

import com.itheima.Pojo.Result;
import com.itheima.Pojo.Student;
import com.itheima.Service.studentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@CrossOrigin(origins = "*", allowedHeaders = "*", methods = { RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT,
        RequestMethod.DELETE, RequestMethod.OPTIONS })
@RestController
@RequestMapping("/students")
public class studentController {
    @Autowired
    studentService studentService;

    @GetMapping
    public Result getAllStudent() {
        log.info("查询所有学生");
        List<Student> list = studentService.getAllStudent();
        log.info("查询结果：{}", list);
        return Result.success(list != null ? list : new ArrayList<>());
    }

    @PostMapping
    public Result addStudent(@RequestBody Student student) {
        log.info("完整学生数据 - 学号: {} 姓名: {} 班级ID: {} 密码: {}",
                student.getStudentNumber(),
                student.getName(),
                student.getClazzId(),
                student.getPassword());

        try {
            if (student.getPassword() == null) {
                student.setPassword("123456");
            }
            studentService.addStudent(student);
            return Result.success();
        } catch (Exception e) {
            log.error("数据库操作异常", e);
            return Result.error("添加失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        log.info("删除学生");
        studentService.deleteById(id);
        return Result.success();
    }

    @PutMapping
    public Result updateById(@RequestBody Student student) {
        log.info("接收到的更新数据：{}", student);
        log.info("修改学生");
        studentService.update(student);
        return Result.success();
    }

}
